import request from './request'
import list from './index'
import { Message } from 'element-ui'

function getTarget(name) {
  let target = list
  name.split('.').forEach(item => {
    if (!target[item]) console.error(`'${name}' was not found in api module`)
    target = target[item]
  })
  return target
}

async function sendRequest(name, data = '') {
  const target = getTarget(name)
  if (!target.url) throw new Error(`Invalid property 'url' of '${name}'`)
  const output = (res) => {
    return new Promise((resolve, reject) => {
      res.success === true ? resolve(res) : Message({ message: res.message, type: 'error' })
      reject(res.message)
    })
  }

  // 根据不同的类型，进行参数拼接和执行不同的方法
  let result = { }
  switch (target.method) {
    case 'post':
    case 'put': {
      let type = null
      target.method === 'put' ? type = 'put' : type = 'post'
      await request[type](target.url, data).then(res => {
        result = res
      })
      break
    }
    case 'delete':
    case 'get': {
      let type = null
      target.method === 'get' ? type = 'get' : type = 'delete'
      await request[type](`${target.url}/${data}`).then(res => {
        result = res
      })
      break
    }
    default:
      throw new Error(`Invalid property 'methods' of ${name}`)
  }
  return output(result)
}

export default {
  install: function(Vue) {
    Vue.prototype.$api = (name, data) => sendRequest(name, data)
  },
  sendRequest
}
